#/bin/bash

DVDWRITER="/dev/hda"
NOW=`date +%s`
TMP_DIR="/tmp/vf2dvd${NOW}"


function usage()
{
	echo "$0 <src_video_file>"
	exit 1
}

function check_last_retcode()
{
	if [ $1 -ne 0 ]
	then
		echo "$2"
		exit 1
	fi
}

# Заданы ли все параметры
if [ $# -ne 1 ]
then
	usage
fi

# Проверяем доступность необходимых программ
MOVIE_TO_DVD=`which movie-to-dvd`
check_last_retcode $? "ERROR: movie-to-dvd not found. Please, install VideoTrans package."

DVDAUTHOR=`which dvdauthor`
check_last_retcode $? "ERROR: dvdauthor not found. Please, install dvdauthor package."

GENISOIMAGE=`which genisoimage`
check_last_retcode $? "ERROR: genisoimage not found. Please, install cdrkit package."

WODIM=`which wodim`
check_last_retcode $? "ERROR: wodim not found. Please, install cdrkit package."

# Существует ли исходный файл
if [ ! -f $1 ]
then
	echo "ERROR: can't open source file '$1'"
	exit 1
fi

# Если ли право на запись во временной каталог
mkdir ${TMP_DIR}
check_last_retcode $? "ERROR: can't create tmp directory '${TMP_DIR}'"

# Транскодируем файл
${MOVIE_TO_DVD} -M -m pal -o ${TMP_DIR} $1
check_last_retcode $? "ERROR: can't transcode '$1'"

# Создаем XML файл для DVDAuthor
VOBFILE=`ls ${TMP_DIR}/*vob`
echo "<dvdauthor>" > ${TMP_DIR}/dvdauthor.xml
echo "<vmgm />" >> ${TMP_DIR}/dvdauthor.xml
echo "<titleset>" >> ${TMP_DIR}/dvdauthor.xml
echo "<titles>" >> ${TMP_DIR}/dvdauthor.xml
echo "<pgc>" >> ${TMP_DIR}/dvdauthor.xml
echo "<vob file=\"${VOBFILE}\" />" >> ${TMP_DIR}/dvdauthor.xml
echo "</pgc>" >> ${TMP_DIR}/dvdauthor.xml
echo "</titles>" >> ${TMP_DIR}/dvdauthor.xml
echo "</titleset>" >> ${TMP_DIR}/dvdauthor.xml
echo "</dvdauthor>" >> ${TMP_DIR}/dvdauthor.xml

# Авторинг
${DVDAUTHOR} -o ${TMP_DIR}/dvd_structure -x ${TMP_DIR}/dvdauthor.xml
check_last_retcode $? "ERROR: can't processing '$1' by dvdauthor"

# Создаем образ для записи
${GENISOIMAGE} -dvd-video -o ${TMP_DIR}/dvdimage.iso ${TMP_DIR}/dvd_structure
check_last_retcode $? "ERROR: can't create image file from ${TMP_DIR}/dvd_structure"

# Пишем образ
${WODIM} -dev=${DVDWRITER} ${TMP_DIR}/dvdimage.iso
check_last_retcode $? "ERROR: can't write ${TMP_DIR}/dvdimage.iso to ${DVDWRITER}"

# Удаляем временной каталог со всем барахлом
rm -rf ${TMP_DIR}
